package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.bugtags.library.Bugtags;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.ImageTools;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.ProblemBackOriginal;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.FileNetWorkUtil;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.io.File;
import java.util.HashMap;
import org.json.JSONException;

/**
 * Created by lenovo on 2016/11/17.
 * 问题反馈
 */
public class ProblemBackDetailFragment extends Fragment implements View.OnClickListener {
  private static final int REQUEST_RP1 = 1;
  private static final int REQUEST_RP2 = 2;
  private static final int REQUEST_RP3 = 3;
  private static final int REQUEST_RP4 = 4;
  private static final int NEW = 0;
  private static final int SUBMIT = 1;
  private static final int PUBLISH = 2;
  private static final int TYPE_SAVE = 3;
  private static final int TYPE_OTHER = 4;

  protected String selcurFile = "";//文件上传服务器返回路径
  protected String mFilePath1 = "";//文件本地路径
  protected String mFilePath2 = "";//文件本地路径
  protected String mFilePath3 = "";//文件本地路径
  protected String mFilePath4 = "";//文件本地路径
  private ProblemBackOriginal.ProblemBackContent content;
  private BaseVolleyActivity mActivity;
  private CurrentUser mUser;
  private int menuType;
  private EditText mEtResname;
  private EditText mEtFeedback;
  private EditText mEtRemark;
  private TextView mTvIfReply;
  private TextView mTvDataStatus;
  private TextView mTvRegStaffName;
  private TextView mTvRegDate;
  private TextView mTvRp1;
  private ImageView mIvExtra1;
  private TextView mTvRp2;
  private ImageView mIvExtra2;
  private TextView mTvRp3;
  private ImageView mIvExtra3;
  private TextView mTvRp4;
  private ImageView mIvExtra4;

  protected static ProblemBackDetailFragment newInstence(
      ProblemBackOriginal.ProblemBackContent content) {
    ProblemBackDetailFragment mfragment = new ProblemBackDetailFragment();
    Bundle bundle = new Bundle();
    bundle.putSerializable(ProblemBackListFragment.EXTRA_VALUE, content);
    mfragment.setArguments(bundle);
    return mfragment;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    mActivity = (BaseVolleyActivity) getActivity();
    ActionBar actionBar = mActivity.getSupportActionBar();
    if (actionBar != null) {
      actionBar.setTitle(R.string.back_detail);
      actionBar.setDisplayHomeAsUpEnabled(true);
    }

    mUser = CurrentUser.newInstance(getActivity());
    content = (ProblemBackOriginal.ProblemBackContent) getArguments().getSerializable(
        ProblemBackListFragment.EXTRA_VALUE);
    if (content != null) {
      if (DataStatus.NEW.equalsIgnoreCase(content.getDataStatus())
          || DataStatus.ABORT.equalsIgnoreCase(content.getDataStatus())) {
        menuType = NEW;
      } else if (DataStatus.SUBMIT.equalsIgnoreCase(content.getDataStatus())) {
        menuType = SUBMIT;
      } else {
        menuType = PUBLISH;
      }
    }
    super.onCreate(savedInstanceState);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    switch (menuType) {
      //草稿状态：保存、启动流程、删除
      case NEW:
        inflater.inflate(R.menu.menu_save_submit_delete, menu);
        break;
      //提交状态：终止
      case SUBMIT:
        inflater.inflate(R.menu.menu_stop, menu);
        break;
      //已完成状态：
      case PUBLISH:
        break;
      default:
        break;
    }

    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_problemback_detail, container, false);
    findViews(view);
    initData();
    return view;
  }

  private void findViews(View view) {
    mEtResname = (EditText) view.findViewById(R.id.et_resname);
    mEtFeedback = (EditText) view.findViewById(R.id.et_feedback);
    mEtRemark = (EditText) view.findViewById(R.id.et_remark);
    mTvIfReply = (TextView) view.findViewById(R.id.tv_ifReply);
    mTvDataStatus = (TextView) view.findViewById(R.id.tv_titleRight);
    mTvRegStaffName = (TextView) view.findViewById(R.id.tv_regStaffName);
    mTvRegDate = (TextView) view.findViewById(R.id.tv_regDate);
    //附件
    mTvRp1 = (TextView) view.findViewById(R.id.tv_rp1);
    mIvExtra1 = (ImageView) view.findViewById(R.id.iv_extra1);
    mTvRp2 = (TextView) view.findViewById(R.id.tv_rp2);
    mIvExtra2 = (ImageView) view.findViewById(R.id.iv_extra2);
    mTvRp3 = (TextView) view.findViewById(R.id.tv_rp3);
    mIvExtra3 = (ImageView) view.findViewById(R.id.iv_extra3);
    mTvRp4 = (TextView) view.findViewById(R.id.tv_rp4);
    mIvExtra4 = (ImageView) view.findViewById(R.id.iv_extra4);
  }

  private void initData() {
    mEtResname.setText(content.getResname());
    mEtFeedback.setText(content.getFeedback());
    mEtRemark.setText(content.getRemark());
    if ("F".equalsIgnoreCase(content.getIfReply())) {
      mTvIfReply.setText(R.string.no);
    } else if ("T".equalsIgnoreCase(content.getIfReply())) {
      mTvIfReply.setText(R.string.yes);
    }
    if (DataStatus.NEW.equalsIgnoreCase(content.getDataStatus())) {
      mTvDataStatus.setText(R.string.draft);
    } else if (DataStatus.SUBMIT.equalsIgnoreCase(content.getDataStatus())) {
      mTvDataStatus.setText(R.string.handle);
    } else if (DataStatus.PUBLIS.equalsIgnoreCase(content.getDataStatus())) {
      mTvDataStatus.setText(R.string.hasFinishplan);
    } else if (DataStatus.ABORT.equalsIgnoreCase(content.getDataStatus())) {
      mTvDataStatus.setText(R.string.aborted);
    } else {
      mTvDataStatus.setText(R.string.errData);
    }
    mTvRegStaffName.setText(content.getRegStaffName());
    mTvRegDate.setText(content.getRegDate());
    if (DataStatus.SUBMIT.equalsIgnoreCase(content.getDataStatus())
        || DataStatus.SUBMIT.equalsIgnoreCase(content.getDataStatus())
        || DataStatus.SUBMIT.equalsIgnoreCase(content.getDataStatus())) {
      mEtFeedback.setEnabled(false);
      mEtResname.setEnabled(false);
      mEtRemark.setEnabled(false);
    }
    mTvRp1.setText(FileUtil.getFileNameByFilePath(content.getResourcePath1()));
    mTvRp2.setText(FileUtil.getFileNameByFilePath(content.getResourcePath2()));
    mTvRp3.setText(FileUtil.getFileNameByFilePath(content.getResourcePath3()));
    mTvRp4.setText(FileUtil.getFileNameByFilePath(content.getResourcePath4()));
    if (DataStatus.NEW.equalsIgnoreCase(content.getDataStatus())
        || DataStatus.ABORT.equalsIgnoreCase(content.getDataStatus())) {
      mIvExtra1.setVisibility(View.VISIBLE);
      mIvExtra2.setVisibility(View.VISIBLE);
      mIvExtra3.setVisibility(View.VISIBLE);
      mIvExtra4.setVisibility(View.VISIBLE);
    }

    //选择附件
    mIvExtra1.setOnClickListener(this);
    mIvExtra2.setOnClickListener(this);
    mIvExtra3.setOnClickListener(this);
    mIvExtra4.setOnClickListener(this);
    //附件下载
    mTvRp1.setOnClickListener(this);
    mTvRp2.setOnClickListener(this);
    mTvRp3.setOnClickListener(this);
    mTvRp4.setOnClickListener(this);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      //保存
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;
      //保存
      case R.id.menu_item_save:
        if (mUser.getJobNumber().equalsIgnoreCase(content.getRegStaffId())) {
          volleyPostSave(false);
        } else {
          ToastUtil.show(R.string.no_staffName);
        }
        break;
      //启动流程
      case R.id.menu_item_submit:
        if (mUser.getJobNumber().equalsIgnoreCase(content.getRegStaffId())) {
          //volleyPostSubmit();
          volleyPostSave(true);
        } else {
          ToastUtil.show(R.string.no_staffName);
        }

        break;
      //删除
      case R.id.menu_item_delete:
        if (mUser.getJobNumber().equalsIgnoreCase(content.getRegStaffId())) {
          volleyPostDelete();
        } else {
          ToastUtil.show(R.string.no_staffName);
        }
        break;

      //终止流程
      case R.id.menu_item_stop:
        if (mUser.getJobNumber().equalsIgnoreCase(content.getRegStaffId())) {
          volleyPostStop();
        } else {
          ToastUtil.show(R.string.no_staffName);
        }
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  //终止流程
  private void volleyPostStop() {
    String delUrl = ApiConst.getAbsoluteUrl(ApiConst.URL_TASK_STOP);
    HashMap<String, String> params = new HashMap<>();
    params.put("runId", content.getRunId());
    MyUtils.showDialogLoading(getActivity(), R.string.interrupting);
    mActivity.volleyPost(delUrl, params, getResponse(TYPE_OTHER, false));
  }

  //删除
  private void volleyPostDelete() {
    String delUrl = ApiConst.getAbsoluteUrl(ApiConst.URL_PROBLEM_BACK_DEL);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", content.getId());
    MyUtils.showDialogLoading(getActivity(), R.string.loadingDelete);
    mActivity.volleyPost(delUrl, params, getResponse(TYPE_OTHER, false));
  }

  //启动流程
  private void volleyPostSubmit() {
    String startUrl = ApiConst.getAbsoluteUrl(ApiConst.URL_PROBLEM_BACK_START);
    HashMap<String, String> params = new HashMap<>();
    params.put("idList", "1");
    params.put("id", content.getId());
    MyUtils.showDialogLoading(getActivity(), R.string.loadingStart);
    mActivity.volleyPost(startUrl, params, getResponse(TYPE_OTHER, false));
  }

  //保存
  private void volleyPostSave(boolean isSaveAndSubmit) {
    String saveUrl = ApiConst.getAbsoluteUrl(ApiConst.URL_PROBLEM_BACK_SUB);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", content.getId());
    params.put("dataStatus", content.getDataStatus());
    params.put("feedback", mEtFeedback.getText().toString());
    params.put("resname", mEtResname.getText().toString());
    params.put("remark", mEtRemark.getText().toString());

    params.put("resourcePath1", content.getResourcePath1());
    params.put("resourcePath2", content.getResourcePath2());
    params.put("resourcePath3", content.getResourcePath3());
    params.put("resourcePath4", content.getResourcePath4());

    CurrentUser user = CurrentUser.newInstance(mActivity);
    Bugtags.sendFeedback(
        MyStringUtil.connect(user.getName(), getString(R.string.comma), user.getPassword(),
            params.toString()));
    MyUtils.showDialogLoading(getActivity(), R.string.loadingSave);
    mActivity.volleyPost(saveUrl, params, getResponse(TYPE_SAVE, isSaveAndSubmit));
  }

  private VolleyResponse getResponse(final int type, final boolean isSaveAndSubmit) {
    return new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        try {
          MyUtils.dismissDialog();
          //解析
          SuccessMessage result = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == result || null == result.getResult()) {
            ToastUtil.show(R.string.failure_operation);
            return;
          }
          String successType = result.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            ToastUtil.show(result.getMessage());
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            if (TYPE_SAVE == type) {
              //上传附件
              if (!TextUtils.isEmpty(mFilePath1)) {
                upLoad(mFilePath1, true, "resourcePath1");
              }
              if (!TextUtils.isEmpty(mFilePath2)) {
                upLoad(mFilePath2, true, "resourcePath2");
              }
              if (!TextUtils.isEmpty(mFilePath3)) {
                upLoad(mFilePath3, false, "resourcePath3");
              }
              if (!TextUtils.isEmpty(mFilePath4)) {
                upLoad(mFilePath4, false, "resourcePath4");
              }
            }
            ToastUtil.show(R.string.success_operation);
            if (isSaveAndSubmit) {
              volleyPostSubmit();
            } else {

              getActivity().setResult(Activity.RESULT_OK);
              getActivity().finish();
            }
          }
        } catch (JsonSyntaxException e) {
          ToastUtil.show(R.string.wrong_data);
        }
      }
    };
  }

  @Override public void onClick(View view) {
    switch (view.getId()) {
      //图片一
      case R.id.tv_rp1:
        downFile(content.getResourcePath1());
        break;
      case R.id.iv_extra1:
        choosePicture(REQUEST_RP1);
        break;
      //图片二
      case R.id.tv_rp2:
        downFile(content.getResourcePath2());
        break;
      case R.id.iv_extra2:
        choosePicture(REQUEST_RP2);
        break;
      //其他一
      case R.id.tv_rp3:
        downFile(content.getResourcePath3());
        break;
      case R.id.iv_extra3:
        chooseFile(REQUEST_RP3);
        break;
      //其他二
      case R.id.tv_rp4:
        downFile(content.getResourcePath4());
        break;
      case R.id.iv_extra4:
        chooseFile(REQUEST_RP4);
        break;
    }
  }

  protected void upLoad(String path, boolean isPicture, String resourcePath) {

    //        new FileNetWorkUtil(getActivity())
    //                .upLoadFile(path, ApiConst.URL_UPLOAD_FILE, null, "app", "sys_error_feedback", mId, null, true);

    new FileNetWorkUtil(getActivity()).upLoadFilePath(path, ApiConst.URL_UPLOAD_FILE, null, "app",
        "bpmx.sys_error_feedback", content.getId(), null, isPicture, resourcePath);
  }

  private void downFile(String serverPath) {
    if (!TextUtils.isEmpty(serverPath)) {
      ExtraDownLoadDialogFragment dialog = ExtraDownLoadDialogFragment.newInstance("", serverPath);
      FragmentManager fm = getActivity().getSupportFragmentManager();
      dialog.show(fm, "");
    }
  }

  private void chooseFile(int requestCode) {
    Intent intent2 = new Intent(Intent.ACTION_GET_CONTENT);
    intent2.setType("*/*");
    intent2.addCategory(Intent.CATEGORY_OPENABLE);
    startActivityForResult(Intent.createChooser(intent2, getString(R.string.chooseFileExplorer)),
        requestCode);
  }

  private void choosePicture(int requestCode) {
    // 调用图库
    Intent intent = new Intent(Intent.ACTION_PICK, null);
    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
    startActivityForResult(intent, requestCode);
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    //        if (requestCode == REQUEST_ALBUM) {
    //            Uri uri = data.getData();
    //            path = FileUtil.getPath(getActivity(), uri);
    //            LogUtil.i("oldpath=" + path);
    //            Bitmap bm = BitmapFactory.decodeFile(path);
    //            if (bm == null) {
    //                Toast.makeText(getActivity(), "bitmap==null",
    //                        Toast.LENGTH_SHORT).show();
    //                return;
    //            }
    //            Bitmap mNewBitmap = ImageTools.zoomBitmap(bm, 400, 400);// 压缩图片
    //            bm.recycle();
    //
    //            mIvPhotoProblem.setImageBitmap(mNewBitmap);
    //            mIvPhotoProblem.setVisibility(View.VISIBLE);
    //            // 将压缩的图片重新保存
    //            File file = ImageTools.savePhotoToSDCard(mNewBitmap,
    //                    FileUtil.getFileDir(), System.currentTimeMillis() + "");
    //            path = file.getAbsolutePath();
    //            LogUtil.i("newpath=" + path);
    //        }

    if (requestCode == REQUEST_RP1) {
      mFilePath1 = getPicture(data);
      String mChoseFileName = FileUtil.getFileNameByFilePath(mFilePath1);
      mTvRp1.setText(mChoseFileName);
    }
    if (requestCode == REQUEST_RP2) {
      mFilePath2 = getPicture(data);
      String mChoseFileName = FileUtil.getFileNameByFilePath(mFilePath2);
      mTvRp2.setText(mChoseFileName);
    }
    if (requestCode == REQUEST_RP3) {
      mFilePath3 = getFile(data);
      String mChoseFileName = FileUtil.getFileNameByFilePath(mFilePath3);
      mTvRp3.setText(mChoseFileName);
    }
    if (requestCode == REQUEST_RP4) {
      mFilePath4 = getFile(data);
      String mChoseFileName = FileUtil.getFileNameByFilePath(mFilePath4);
      mTvRp4.setText(mChoseFileName);
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  private String getPicture(Intent data) {
    Uri uri = data.getData();
    String path = FileUtil.getPath(getActivity(), uri);
    Bitmap bm = BitmapFactory.decodeFile(path);
    if (bm == null) {
      Toast.makeText(getActivity(), "bitmap==null", Toast.LENGTH_SHORT).show();
      return "";
    }
    Bitmap mNewBitmap = ImageTools.zoomBitmap(bm, 400, 400);// 压缩图片
    bm.recycle();
    // 将压缩的图片重新保存
    File file = ImageTools.savePhotoToSDCard(mNewBitmap, FileUtil.getFileDir(),
        System.currentTimeMillis() + "");
    if (file != null) {
      return file.getAbsolutePath();
    }
    return "";
  }

  private String getFile(Intent data) {
    String path1 = FileUtil.getPath(getActivity(), data.getData());
    File mFile = null;
    if (path1 != null) {
      mFile = new File(path1);
    }
    if (null == mFile) {
      Toast.makeText(getActivity(), R.string.fileNotFound, Toast.LENGTH_SHORT).show();
      return "";
    }
    return mFile.getAbsolutePath();
  }
}
